﻿#region Using

using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

#endregion

namespace Commons.Extension
{
    public static class XmlExtension
    {
        /// <summary> 
        /// Converte um objeto para XmlDocument. 
        /// </summary> 
        /// <param name="aObject">Objeto a ser convertido.</param> 
        /// <returns>Retorna o XmlDocument convertido.</returns> 
        public static XmlDocument XmlSerialize( this object aObject )
        {
            XmlDocument lObjectToXmlDocument = new XmlDocument();

            using ( MemoryStream lMemoryStream = new MemoryStream() )
            {
                using ( StreamWriter lStreamWriter = new StreamWriter( lMemoryStream, Encoding.UTF8 ) )
                {
                    XmlSerializer lXmlSerializer = new XmlSerializer( aObject.GetType() );

                    lXmlSerializer.Serialize( lStreamWriter, aObject );
                }

                lMemoryStream.Position = 0;

                lObjectToXmlDocument.Load( lMemoryStream );
            }

            return lObjectToXmlDocument;
        }

        /// <summary> 
        /// Converte um XmlDocument para Object. 
        /// </summary> 
        /// <typeparam name="T">Tipo do Objeto.</typeparam> 
        /// <param name="aXmlDocument">XmlDocument a ser convertido</param> 
        /// <returns>Retorna um objeto do tipo T</returns> 
        public static T XmlRestore<T>( this XmlNode aXmlDocument )
        {
            T lXmlDocumentToObject;

            using ( StringWriter lStringWriter = new StringWriter() )
            {
                using ( XmlTextWriter lXmlWriter = new XmlTextWriter( lStringWriter ) )
                {
                    aXmlDocument.WriteTo( lXmlWriter );
                }

                XmlSerializer lXmlSerializer = new XmlSerializer( typeof( T ) );

                using ( MemoryStream lMemoryStream = new MemoryStream( Encoding.UTF8.GetBytes( lStringWriter.ToString() ) ) )
                {
                    lMemoryStream.Position = 0;

                    lXmlDocumentToObject = (T)lXmlSerializer.Deserialize( lMemoryStream );
                }
            }
            
            return lXmlDocumentToObject;
        }
    }
}